package com.lingo.ffmpegdemo.screen.demo;


import com.spicdt.iot.api.entity.FileUploadFile;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

/**
 * https://blog.csdn.net/youanyyou/article/details/118447226
 *
 * https://blog.csdn.net/qq_44874270/article/details/119132425
 * // TODO
 * // TODO
 * // TODO
 * // TODO
 * // TODO
 */
@Slf4j
public class Server {

    private static final File file = new File("C:\\Users\\AdminWatson\\Desktop\\picture\\ss\\2.png");
    private static final int port = 8888;

    public static void main(String[] args) throws Exception {
        FileUploadFile fileUploadFile = new FileUploadFile();
        fileUploadFile.setFile(file);
        fileUploadFile.setFileName(file.getName());
        new Server().serverStart(port, fileUploadFile);
    }

    public void serverStart(int port, final FileUploadFile fileUploadFile) throws InterruptedException {
        //1 第一个线程组 是用于接收client端的连接
        EventLoopGroup bossgroup = new NioEventLoopGroup();
        //2 第二个线程组 用于实际的业务开发处理操作
        EventLoopGroup workgroup = new NioEventLoopGroup();
        //3 创建一个辅助类Bootstrap,就是对我们的server进行一系列的配置
        ServerBootstrap sb = new ServerBootstrap();
        //4 把两个线程组添加进来
        sb.group(bossgroup, workgroup)
                //指定使用NioServerSocketChannl这种类型的通道
                .channel(NioServerSocketChannel.class)
                //一定要使用childHandler去绑定具体的事件处理器
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(new ObjectEncoder());
                        ch.pipeline().addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.weakCachingConcurrentResolver(null))); // 最大长度
                        ch.pipeline().addLast(new ServerHandler(fileUploadFile));
                    }
                });
        //绑定指定的端口 进行监听
        log.info("启动netty Server");
        ChannelFuture f = sb.bind(port).sync();

        f.channel().closeFuture().sync();
        //关闭线程
        bossgroup.shutdownGracefully();
        workgroup.shutdownGracefully();
    }
}
